package com.szf.task.service.api.tencent;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.szf.base.exception.GenericException;
import com.szf.base.service.SpringContextHolder;
import com.szf.mail.bean.Mail;
import com.szf.mail.service.MailManager;
import com.szf.task.entity.AppInfo;
import com.szf.task.entity.Task;
import com.szf.task.entity.TaskResult;
import com.szf.task.service.TaskManager;
import com.szf.task.service.TaskService;
import com.szf.task.service.api.AbstractApiInterface;
import com.szf.util.DateTimeUtil;
import com.szf.util.JsonUtil;
import com.szf.util.MapUtil;
import com.szf.util.UuidGenerator;
import com.szf.util.VelocityServiceUtil;
import com.tencent.weibo.api.StatusesAPI;

public class AreaTimeline extends AbstractApiInterface {
	private String pos;
	private int minuteMax;
	private int lastMinute;
	private int minuteCount = 1;
	private String urlHead = "http://t.qq.com/p/t/";

	public AreaTimeline(Task task, AppInfo app) {
		super(task, app);
		pos = "0";
		minuteMax = app.getRlimit() / 60;
	}

	public boolean get() throws Exception {
		int curMinute = DateTimeUtil.getCurMinute();
		if (curMinute == lastMinute) {
			minuteCount++;
			if (minuteCount >= minuteMax) {
				return false;
			}
		} else {
			lastMinute = curMinute;
			minuteCount = 1;
		}

		StatusesAPI statusesAPI = new StatusesAPI(super.oauth.getOauthVersion());
		String country = MapUtil.getMap(params, "country");
		String province = MapUtil.getMap(params, "province");
		String city = MapUtil.getMap(params, "city");

		/*
		 * country = "1"; province = "35"; city = "5";
		 */

		apiRs = statusesAPI.areaTimeline(oauth, format, pos, "50", country, province, city);
		statusesAPI.shutdownConnection();
		return true;
	}

	@Override
	public void afterGet() throws Exception {
		TaskManager taskManager = SpringContextHolder.getBean(TaskManager.class);
		TaskService taskService = SpringContextHolder.getBean(TaskService.class);
		MailManager mailManager = SpringContextHolder.getBean(MailManager.class);

		logger.info(apiRs);
		task.setLastDate(new Date());
		JSONObject jsonObject = JSONObject.fromObject(apiRs);
		String ret = JsonUtil.getStr(jsonObject, "ret");
		if ("0".equals(ret)) {
			try {
				Pattern p = Pattern.compile(task.getContentKey());
				JSONObject data = jsonObject.getJSONObject("data");

				String pos = JsonUtil.getStr(data, "pos");
				String hasnext = JsonUtil.getStr(data, "hasnext");
				if ("1".equals(hasnext)) {
					pos = "0";
				} else {
					this.pos = pos;
				}

				JSONArray info = data.getJSONArray("info");
				for (int i = 0; i < info.size(); i++) {
					JSONObject sub = info.getJSONObject(i);
					String text = JsonUtil.getStr(sub, "text");
					String id = JsonUtil.getStr(sub, "id");
					String name = JsonUtil.getStr(sub, "name");
					long timestamp = JsonUtil.getLong(sub, "timestamp") * 1000;
					Matcher m = p.matcher(text);
					StringBuffer sb = new StringBuffer();
					if (m.find()) {
						if (taskManager.getWeblogIds().contains(id)) {
							continue;
						} else {
							taskManager.getWeblogIds().add(id);
						}
						m.appendReplacement(sb, "<span style=\"background-color: yellow;\">" + m.group() + "</span>");
						m.appendTail(sb);
						text = sb.toString();

						TaskResult taskResult = new TaskResult();
						taskResult.setTaskId(task.getTaskId());
						taskResult.setCreatedDate(new Date());
						taskResult.setContent(text);
						taskResult.setJson(sub.toString());
						taskResult.setResultId(UuidGenerator.getUuid());
						taskResult.setWebId(id);
						taskResult.setUrl(urlHead + id);

						taskService.addTaskResult(taskResult);

						Map<String, String> model = new HashMap<String, String>();
						model.put("content", text);
						model.put("time", DateTimeUtil.getDate(timestamp));
						model.put("url", urlHead + id);
						model.put("name", name);
						String content = VelocityServiceUtil.mergeTemplateIntoString("mail.vm", model);

						int maxLen = text.length() > 10 ? 10 : text.length();
						Mail mail = new Mail();
						mail.setText(content);
						mail.setSubject(text.substring(0, maxLen));
						mail.setTo(task.getMailTo());
						mailManager.addMail(mail);

						logger.info("get one!");
					}
				}
				task.setLastRs("success");
				taskService.update(task);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		} else {

			String errcode = JsonUtil.getStr(jsonObject, "errcode");
			String msg = JsonUtil.getStr(jsonObject, "msg");
			task.setLastRs("error!errcode:" + errcode + " msg:" + msg);
			taskService.update(task);
			throw new GenericException("task stop!");
		}
	}

}
